<template>
  <el-dialog
    :title="getTitle"
    :visible.sync="innerVisible"
    width="50%"
    center
  >

    <el-form class="el-form-col" :model="editModel" v-if="isEdit" label-position="left" ref="elFormEdit">
      <el-row>
        <el-col v-if="showHeader" :span="24">
          <el-form-item label="服务类型:" label-width="110px">
            <span >{{ serviceText }} </span>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="预约"  label-width="110px" prop="appointTime" :rules="[
                    {required: true, message: '请选择日期', trigger: 'change'}
                  ]">
            <el-date-picker :picker-options="pickerOptions" type="date" placeholder="选择年月日" v-model="editModel.appointTime" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="20" :offset="4">
          <el-form-item prop="timeCode" :rules="[
                    {required: true, message: '请选择时间段', trigger: 'change'}
                  ]">
            <el-radio-group v-model="editModel.timeCode">
              <el-radio v-for="item in timeCodeArr" :key="item.value" :label="item.value">{{ item.text }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="hasMemo" :span="24">
          <el-form-item label="预约备注" label-width="110px" prop="memo">
            <el-input type="textarea" :maxlength="300"  placeholder="预约备注" v-model="editModel.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-form v-if="!isEdit" class="el-form-col" :model="model" label-position="left" ref="elForm">
      <el-row>

        <template v-if="showHeader">
          <el-col :span="24">
            <el-form-item label="基础服务:" label-width="110px">
              <span v-if="serviceType.length > 0" :key="item" v-for="item in serviceType">{{ item | filterDataBaseDictionary }}&nbsp;&nbsp; </span>
              <span v-if="serviceType.length == 0">无</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item v-if="!isBatch" label="增值服务:" label-width="110px">
            <span v-for="item in otherServices" :key="item">
              <span>{{item|filterDataBaseDictionary}} &nbsp;&nbsp;</span>
            </span>
              <span v-if="otherServices.length === 0">无</span>
              <span style="color:darkgrey" v-if="hasInstallAndPs">&nbsp;&nbsp;&nbsp;&nbsp;在含有配装服务中，所有增值服务在安装调度中调度</span>
              <span style="color:darkgrey" v-if="(hasInstall || hasPs) && !hasInstallAndPs">&nbsp;&nbsp;&nbsp;&nbsp;单独预约后，所有增值服务在安装调度中调度</span>
            </el-form-item>
            <template v-if="hasOrderSourceCodeScm">
              <el-form-item>
                <el-col :span="7">
                  <span>有来源scm的订单只能一体预约</span>
                </el-col>
              </el-form-item>
            </template>
            <template v-if="!hasOrderSourceCodeScm">
              <el-form-item v-if="hasInstallAndPs">
                <el-radio-group v-model="type">
                  <el-col :span="7"><el-radio label="YT">配装一体</el-radio></el-col>
                  <!-- 有来源于 scm 的订单只能配装一体（张伟荣） -->
                  <el-col :span="7" :offset="10">
                    <el-radio  label="FL">配装分离</el-radio>
                  </el-col>
                </el-radio-group>
              </el-form-item>

              <el-form-item v-if="isEmptyServiceType && !isBatch">
                <el-radio-group v-model="emptyType">
                  <el-col :span="7"><el-radio label="ZT">整体预约</el-radio></el-col>
                  <!-- 有来源于 scm 的订单只能配装一体（张伟荣） -->
                  <el-col :span="7" :offset="10">
                    <el-radio  label="DD">单独预约</el-radio>
                  </el-col>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="单独预约:" label-width="110px" v-if="canSingleAppoint">
                <el-checkbox-group v-model="checkedServices" class="pull-left">
                  <!-- 基础服务-->
                  <el-checkbox disabled :key="item" v-for="item in serviceType" :label="item">{{item|filterDataBaseDictionary}}</el-checkbox>
                  <!-- 增值服务 -->
                  <el-checkbox :key="item" v-for="item in otherServices" :label="item">{{item|filterDataBaseDictionary}}</el-checkbox>
                </el-checkbox-group>
                <el-tooltip class="pull-right" content="增值服务预约时间默认与安装相同，勾选表示该项服务需要单独预约" placement="top" effect="light" v-if="hasInstallAndPs">
                  <span style="font-size: 18px"><i class="el-icon-question"></i></span>
                </el-tooltip>
                <el-tooltip class="pull-right" content="勾选增值服务，表示该项服务需要单独预约。" placement="top" effect="light" v-if="!hasInstallAndPs">
                  <span style="font-size: 18px"><i class="el-icon-question"></i></span>
                </el-tooltip>
                <div class="clearfix"></div>
              </el-form-item>
            </template>
          </el-col>
        </template>
      </el-row>
      <el-row v-for="(item, index) in model.appointTimes" :key="item.type">
        <el-col :span="24">
          <el-form-item :label="getTimeLabelText(item.serviceNo)"  label-width="110px" :prop="'appointTimes.' + index + '.time'" :rules="[
                    {required: true, message: '请选择日期', trigger: 'change'}
                  ]">
            <el-date-picker :picker-options="pickerOptions" type="date" placeholder="选择年月日" v-model="item.time" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="20" :offset="4">
          <el-form-item :prop="'appointTimes.' + index + '.timeCode'" :rules="[
                    {required: true, message: '请选择时间段', trigger: 'change'}
                  ]">
            <el-radio-group v-model="item.timeCode">
              <el-radio v-for="item in timeCodeArr" :key="item.value" :label="item.value">{{ item.text }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="hasMemo">
        <el-col :span="24">
          <el-form-item label="预约备注" label-width="110px" prop="memo">
            <el-input type="textarea" :maxlength="300"  placeholder="预约备注" v-model="model.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="hide">取消</el-button>
      <el-button type="primary" @click="postSubmit" :loading="loading">确认提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {filterDataBaseDictionary, unixTimestampFilter} from '@/filters'
import {dotData, isEqual, copy, arrayColumn, confirm, alert} from '@/utils'
import {chTimeIntervalGT} from '@/utils/validatorUtil'
import {getTimeInterval} from '@/utils/selectOptions'
import moment from 'moment'
export default {
  filters: {
    filterDataBaseDictionary
  },
  data() {
    return {
      innerVisible: false,
      model: {
        appointTimes: [],
        memo: ''
      },
      editModel: {
        appointTime: '',
        timeCode: '',
        memo: ''
      },
      checkedServices: [],
      timeCodeArr: [],
      type: '',
      emptyType: '',
      isShowMsg: false,
      loading: false,
      pickerOptions: {
        disabledDate(time) {
          return moment(time).isBefore(Date.now(), 'day')
        }
      }
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rows: {
      type: Array,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    // 暂时上面的服务信息
    showHeader: {
      type: Boolean,
      default: true
    },
    coverTitle: {
      type: String,
      default: ''
    },
    createUrl: {
      type: String,
      default: '/ms-terminal-order/appoint/action'
    },
    hasMemo: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听 传进来的 visible
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      // 初始化清空值
      this.model.appointTimes = []
      this.resetElFormEdit()
      this.$nextTick(_ => {
        this.checkedServices = this.serviceType
        this.setModelCheckList(this.checkList)
        this.setEmptyType()
        this.innerVisible = val
        if (this.isEdit) {
          this.editModel.appointTime = this.appointTime
          this.editModel.timeCode = this.timeCode
          this.editModel.memo = this.memo
        } else {
          this.model.memo = ''
        }
      })
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    },
    hasInstallAndPs(val, oldVal) {
      if (val) {
        this.type = 'YT'
      } else {
        this.type = ''
      }
    },
    isEmptyServiceType(val, oldVal) {
      this.setEmptyType()
    },
    checkList(val, oldVal) {
      if (!isEqual(val, oldVal)) {
        this.setModelCheckList(val)
      }
    }
  },
  computed: {
    getTitle() {
      if (this.coverTitle) {
        return this.coverTitle
      }
      if (this.isEdit) {
        return '改约'
      }
      let title = '预约'
      if (this.isBatch) {
        title = '批量' + title
      }
      return title
    },
    // 是否是批量操作
    isBatch() {
      return Array.isArray(this.rows) && this.rows.length > 1
    },
    // 能单独预约不
    canSingleAppoint() {
      return !this.isBatch && this.type !== 'YT' && !this.isEmptyServiceType
    },
    // 取 传进来的基础服务类型
    serviceType() {
      return arrayColumn(dotData(this.rows, '[0].baseServiceNo'), 'key') || []
    },
    // 是否含安装
    hasInstall() {
      return Array.isArray(this.serviceType) && this.serviceType.indexOf('ZpsServiceType02') >= 0
    },
    // 是否含配送
    hasPs() {
      return Array.isArray(this.serviceType) && this.serviceType.indexOf('ZpsServiceType01') >= 0
    },
    // 是否 无基础服务
    isEmptyServiceType() {
      return Array.isArray(this.serviceType) && this.serviceType.length === 0
    },
    // 取出传进来的增值服务
    otherServices() {
      return arrayColumn(dotData(this.rows, '[0].addedServiceNo'), 'key') || []
    },
    // 是否同时含 安+配送
    hasInstallAndPs() {
      return this.hasInstall && this.hasPs
    },
    // 根据 上面的条件 计算出需要渲染出怎样的数组
    checkList() {
      if (this.isEmptyServiceType) {
        if (this.emptyType === 'DD' && !this.isBatch) {
          return this.otherServices
        }
        return ['ZT']
      } else if (this.type === 'YT') {
        return ['YT']
      } else {
        return this.checkedServices
      }
    },
    idArr() {
      return arrayColumn(this.rows, 'id')
    },
    serviceText() {
      return dotData(this.rows, '[0].service')
    },
    appointTime() {
      let temp = dotData(this.rows, '[0].appointTime')
      if (temp) {
        return unixTimestampFilter(temp, 'YYYY-MM-DD')
      }
      return ''
    },
    timeCode() {
      return dotData(this.rows, '[0].timeIntervalCode') || ''
    },
    // 备注
    memo() {
      return dotData(this.rows, '[0].memo') || ''
    },
    // 来源于scm的订单
    hasOrderSourceCodeScm() {
      for (let v of this.rows) {
        if (v.orderSourceCode === 'scm') {
          return true
        }
      }
      return false
    }
  },
  created() {
    getTimeInterval().then(arr => {
      this.timeCodeArr = arr
    })
  },
  methods: {
    hide() {
      this.innerVisible = false
    },
    getTimeLabelText(type) {
      if (type === 'YT') {
        return '配装一体'
      } else if (type === 'ZT') {
        return '整体预约'
      } else if (type === 'SCM') {
        return '预约'
      }
      return filterDataBaseDictionary(type) + '预约'
    },
    postSubmit() {
      if (this.isEdit) {
        this.$refs.elFormEdit.validate(valid => {
          if (!valid) {
            return
          }
          let data = copy(this.editModel, true)
          data.id = dotData(this.idArr, 0)
          this.loading = true
          this.$ajax.post('/ms-terminal-order/appoint/reappoint-action', data).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              confirm('改约成功').finally(_ => {
                this.hide()
                this.loading = false
                this.$emit('refresh', true)
              })
            } else {
              this.loading = false
            }
          }).catch(_ => {
            this.loading = false
          })
        })
      } else {
        this.$refs.elForm.validate((valid) => {
          if (!valid) {
            return
          }
          let data = copy(this.model, true)
          let appointTimes = dotData(data, 'appointTimes')
          if (Array.isArray(appointTimes)) {
            let PsRow = ''
            // ZpsServiceType01 配送
            for (let v of appointTimes) {
              if (v['serviceNo'] === 'ZpsServiceType01') {
                PsRow = v
                break
              }
            }
            if (PsRow) {
              for (let v of appointTimes) {
                if (v['serviceNo'] !== 'ZpsServiceType01') {
                  if (v['time'] <= PsRow['time']) {
                    if (v['time'] < PsRow['time']) {
                      alert('安装和安装中的增值服务预约时间不能早于配送时间')
                      return
                    }
                    if (chTimeIntervalGT(PsRow['timeCode'], v['timeCode'])) {
                      alert('安装和安装中的增值服务预约时间不能早于配送时间')
                      return
                    }
                  }
                }
              }
            }
          }
          // 安装和安装中的增值服务预约时间不能早于配送时间
          this.loading = true
          data.ids = this.idArr
          if (this.type) {
            data.appointType = this.type
          }
          // 如何有来源于 scm 的订单 去掉 appointType（张伟荣）
          if (this.hasOrderSourceCodeScm) {
            data.appointType = ''
          }
          this.$ajax.post(this.createUrl, data).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              confirm('预约成功').finally(_ => {
                this.hide()
                this.loading = false
                this.$emit('refresh', true)
              })
            } else {
              this.loading = false
            }
          }).catch(_ => {
            this.loading = false
          })
        })
      }
    },
    setModelCheckList(list) {
      // 如果来源于scm 只能整体预约
      if (this.hasOrderSourceCodeScm) {
        this.model.appointTimes = [
          {
            serviceNo: 'SCM',
            time: '',
            timeCode: ''
          }
        ]
        return
      }
      let typeMap = new Map()
      if (Array.isArray(this.model.appointTimes)) {
        this.model.appointTimes.forEach(v => {
          let serviceNo = dotData(v, 'serviceNo')
          if (serviceNo) {
            typeMap.set(serviceNo, v)
          }
        })
      }
      let checkListMap = new Map()
      if (Array.isArray(list)) {
        list.forEach(v => {
          if (!typeMap.has(v)) { // typeMap里面没有type, 但model里面有这个type（model里面的type要保持一致）
            this.model.appointTimes.push({
              serviceNo: v,
              time: '',
              timeCode: ''
            })
          }
          checkListMap.set(v, v)
        })
      }
      // 如果 model里面有的type，但typeMap里面无的type, 那就要把它过滤掉
      this.model.appointTimes = this.model.appointTimes.filter(v => {
        let serviceNo = dotData(v, 'serviceNo')
        return checkListMap.has(serviceNo)
      })
    },
    // 清空改约数据
    resetElFormEdit() {
      const node = this.$refs.elFormEdit
      if (node) {
        node.resetFields()
      }
    },
    setEmptyType() {
      if (this.isEmptyServiceType) {
        this.emptyType = 'ZT'
      } else {
        this.emptyType = ''
      }
    }
  }
}
</script>
